package cate.game.role.task.guide;

import cate.common.table.d.GDFunc;
import cate.common.table.guide.MainlineRow;
import cate.game.role.Role;
import cate.game.role.RoleDependent;
import cate.game.role.task.TaskGroup;
import cate.game.role.task.TaskItem;
import cate.game.role.task.msg.TaskGroupUpdateResp;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;

import java.util.LinkedList;
import java.util.List;


@NoteClass(value = "主线任务（引导）")
public class Mainline extends RoleDependent {

    @NoteField(value = "当前任务ID")
    public int curTaskId;

    @Override
    public void initialize(Role role) {
        super.initialize(role);
        update();
    }

    public void update() {
        TaskGroup group = role.getTask().getGroup(GDFunc.MAINLINE);

        boolean doneEmpty = group.isDoneEmpty();
        if (curTaskId <= 0) {
            // 默认的任务ID
            curTaskId = role.getGame().table.guide.mainline.first.id;
        }
        MainlineRow tpl = role.getGame().table.guide.mainline.get(curTaskId);
        if (tpl != null) {
            if (doneEmpty) {
                group.addItemNoRepeat(curTaskId, true);
            } else {
                // 之前任务做到头 同时领取了奖励 那么给他加新任务
                if (!group.doneList.isEmpty() && group.doneList.get(0).rewardGot) {
                    addNextTask();
                }
            }
        } else {
            logger.info("任务已经做到头了");
        }
    }

    /**
     * 尝试加入下一个任务
     */
    public void addNextTask() {
        TaskGroup group = role.getTask().getGroup(GDFunc.MAINLINE);
        MainlineRow tpl = role.getGame().table.guide.mainline.get(curTaskId);
        if (tpl == null) {
            return;
        }
        // 查找下一个任务
        MainlineRow nextTpl = role.getGame().table.guide.mainline.get(tpl.nextId);
        if (tpl.nextId > 0 && nextTpl != null) {
            // 如果有下一个任务才删除当前任务完成情况
            group.clear();
            // 这里要读表
            int nextTaskId = tpl.nextId;
            List<TaskItem> list = new LinkedList<>();
            TaskItem taskItem = group.addItemNoRepeat(nextTaskId, true);
            list.add(taskItem);
            curTaskId = tpl.nextId;
            role.sendNow(new TaskGroupUpdateResp(GDFunc.MAINLINE, list));
        }
    }

    /**
     * 重设当前主线任务
     */
    public void replaceCurTask(int nextTaskId) {
        TaskGroup group = role.getTask().getGroup(GDFunc.MAINLINE);
        group.clear();
        group.addItemNoRepeat(nextTaskId, true);
        curTaskId = nextTaskId;
    }

    public int getTaskIndex() {
        MainlineRow row = role.getGame().table.guide.mainline.get(this.curTaskId);
        return row != null ? row.index : 0;
    }
}
